package login

import (
	"context"
	"time"

	"server-go/api/reward/internal/svc"
	"server-go/api/reward/internal/types"
	"server-go/api/reward/internal/util"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type EmailAccountLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewEmailAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EmailAccountLogic {
	return &EmailAccountLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *EmailAccountLogic) EmailAccount(req *types.EmailAccountInput) (resp *types.EmailAccountOutput, err error) {
	resp = new(types.EmailAccountOutput)
	// 登录
	res, err := l.svcCtx.RewardRpc.EmailAccount(l.ctx, &reward.EmailAccountInput{
		PassWord: req.PassWord,
		Email:    req.Email,
	})
	if err != nil {
		return resp, err
	}
	if res.Data != "success" {
		resp.Data = res.Data
		return resp, nil
	}
	// 生成jwt token
	now := time.Now().Unix()
	token, err := util.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, res.BaseUserInfo.UserName, 2, now, l.svcCtx.Config.Auth.AccessExpire)
	if err != nil {
		return resp, err
	}
	resp.Data = res.Data
	resp.BaseUserInfo = &types.Account{
		NickName:  res.BaseUserInfo.NickName,
		Email:     res.BaseUserInfo.Email,
		Gender:    res.BaseUserInfo.Gender,
		UserIntro: res.BaseUserInfo.UserIntro,
		UserName:  res.BaseUserInfo.UserName,
		Money:     res.BaseUserInfo.Money,
		Token:     token,
	}
	return resp, nil
}
